#!/usr/bin/env Python

from __future__ import print_function
from collections import OrderedDict
import smtplib
from email.mime.text import MIMEText
import argparse
import json
import sys
from importlib import reload
import time

import os, time, re, sensors

mem = float(80)
cpu=float(10)
temp=float(50)


last_worktime = 0
last_idletime = 0

sensors.init()
def get_mem_usage_percent():
    try:
        f = open('/proc/meminfo', 'r')
        for line in f:
            if line.startswith('MemTotal:'):
                mem_total = int(line.split()[1])
            elif line.startswith('MemFree:'):
                mem_free = int(line.split()[1])
            elif line.startswith('Buffers:'):
                mem_buffer = int(line.split()[1])
            elif line.startswith('Cached:'):
                mem_cache = int(line.split()[1])
            elif line.startswith('SwapTotal:'):
                vmem_total = int(line.split()[1])
            elif line.startswith('SwapFree:'):
                vmem_free = int(line.split()[1])
            else:
                continue
        f.close()
    except:
        return None
    physical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
    virtual_percent = 0
    if vmem_total > 0:
        virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)
    return physical_percent, virtual_percent

def usage_percent(use, total):
    try:
        ret = (float(use) / total) * 100
    except ZeroDivisionError:
        raise Exception("ERROR - zero division error")
    return ret

def meminfo():

    mem_usage = get_mem_usage_percent()
    mem_usage = mem_usage[0]
    mem_tip = str(mem_usage) + "%"
    return mem_tip

def cpu_use():
    global last_worktime, last_idletime
    f = open("/proc/stat", "r")
    line = ""
    while not "cpu " in line: line = f.readline()
    f.close()
    spl = line.split(" ")
    worktime = int(spl[2]) + int(spl[3]) + int(spl[4])
    idletime = int(spl[5])
    dworktime = (worktime - last_worktime)
    didletime = (idletime - last_idletime)
    rate = float(dworktime) / (didletime + dworktime)
    cpu_t = rate * 100
    last_worktime = worktime
    last_idletime = idletime
    if (last_worktime == 0): return 0
    return cpu_t

def cpu_temperature():
    for chip in sensors.ChipIterator("coretemp-*"):
        i = 0
        sum = 0
        for feature in sensors.FeatureIterator(chip):
            sfi = sensors.SubFeatureIterator(chip, feature)
            vals = [sensors.get_value(chip, sf.number) for sf in sfi]
            sum = sum + vals[0]
            i = i + 1
        return sum / i



def txt(MemFree,cpu_u,cpub):
    f = open('./meminfo.txt', 'a')
    content = '服务器内存--' + str(MemFree) + '\服务器CPU--' + str(cpu_u) + '\服务器温度--' + str(cpub)
    f.write('\n'+content)
    f.seek(0)
    f.close()

if __name__ == '__main__':
    while True:
        MemFree = meminfo()
        cpu_u = cpu_use()
        cpub = cpu_temperature()
        MemFree_res=float(MemFree.split('%',1)[0])
        time.sleep(2)
        if MemFree_res>=mem or cpu_u>=cpu or cpub>=temp:
            txt(MemFree,cpu_u,cpub)
            print(MemFree,cpu_u,cpub)
            time.sleep(1)
        else:
            time.sleep(1)



